import { BusinessTaskMap, IBusiness, IBusinessName, IBusinessStatus } from '../BusinessContext';
import { sendCustomizeMessage } from './requestBusiness';
import Message from '@/utils/message';
import { notification } from 'antd';
import AgentService from '@/modules/Agent';
import { deleteWhiteboard, deletePdfWhiteboard } from './requestBusiness';
import i18next from '../../../utils/i18next/i18n';
import { updateFormRecord } from '@/api';
import { removeCustomerViewMarkContainer } from '@/views/CustomerStreamMark';
const { t } = i18next;

/** 访客响应截图 */
const onScreenShot = (callback: (data: any) => void) => {
	ivcs.agent.onScreenShot(async data => {
		if (data.data.data.url) {
			data.data.data.url = AgentService.configure.replaceStaticUrl(data.data.data.url);
		}

		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 访客响应表单 */
const onFillForm = (callback: (data: any) => void) => {
	ivcs.agent.onFillForm(async data => {
		//更新表单状态
		console.log('onFillForm:', data);

		if (data.data.status !== 'in-progress') {
			let content = {
				id: data.data.data[0].formId,
				status: data.data.status === 'done' ? 'success' : 'fail'
			};
			await updateFormRecord(content);
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 访客响应地理位置 */
const onGeoLocation = (callback: (data: any) => void) => {
	ivcs.agent.onGeoLocation(async data => {
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 访客响应签名 */
const onHandWriting = (callback: (data: any) => void) => {
	ivcs.agent.onHandWriting(async data => {
		console.log('onHandWriting:', data);
		if (data.data.data.pic) {
			data.data.data.pic = AgentService.configure.replaceStaticUrl(data.data.data.pic);
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 访客响应扫码 */
const onScanCode = (callback: (data: any) => void) => {
	ivcs.agent.onScanCode(async data => {
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 访客回复 实时标注接受/拒绝 */
const onCustomerViewMarkResult = (callback: (data: any) => void) => {
	ivcs.agent.onCustomerViewMarkResult(async data => {
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 接收访客查看资源过程/结果 */
const onViewResource = (callback: (data: any) => void) => {
	ivcs.agent.onViewResource(async data => {
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 接收访客的截屏结果*/
const onScreenCapture = (callback: (data: any) => void) => {
	ivcs.agent.onScreenCapture(async data => {
		if (data.data.data.url) {
			data.data.data.url = AgentService.configure.replaceStaticUrl(data.data.data.url);
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

// 接收访客身份证采集结果
const onIdCardCollectResult = (callback: (data: any) => void) => {
	ivcs.agent.onIdCardCollectResult(async data => {
		console.log('onIdCardCollectResult:', data);
		if (data.data.data.urls && data.data.data.urls.length > 0) {
			data.data.data.urls = data.data.data.urls.map((item: any) => {
				item.url = AgentService.configure.replaceStaticUrl(item.url);
				return item;
			});
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};
// 接收访客银行卡采集结果
const onBankCardCollectResult = (callback: (data: any) => void) => {
	ivcs.agent.onBankCardCollectResult(async data => {
		console.log('onBankCardCollectResult:', data);
		if (data.data.data.urls && data.data.data.urls.length > 0) {
			data.data.data.urls = data.data.data.urls.map((item: any) => {
				item.url = AgentService.configure.replaceStaticUrl(item.url);
				return item;
			});
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};
//接收访客证言抄录的过程/结果
const onTestimonyWriteResult = (callback: (data: any) => void) => {
	ivcs.agent.onTestimonyWriteResult(async data => {
		console.log('onTestimonyWriteResult:', data);

		if (data.data.data.data) {
			data.data.data.data = AgentService.configure.replaceStaticUrl(data.data.data.data);
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};
//接收访客变量采集的过程/结果
const onCollectVariableResult = (callback: (data: any) => void) => {
	ivcs.agent.onCollectVariableResult(async (data: any) => {
		if (data.data.status === 'done') {
			const resulut = { userName: data.fromUser.name, data: data.data.data.data, clientId: data.from, userRole: data.data.data.role };
			AgentService.responseVariabelData = [...AgentService.responseVariabelData, resulut];
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};
//接收访客共享白板的过程/结果
const onWhiteboardResult = (callback: (data: any) => void) => {
	ivcs.agent.onWhiteboardResult(async data => {
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};
//接收访客共享pdf白板的过程/结果
const onPdfWhiteboardResult = (callback: (data: any) => void) => {
	ivcs.agent.onPdfWhiteboardResult(async data => {
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};
//接收短视频采集的过程/结果
const onCollectShortVideoResult = (callback: (data: any) => void) => {
	ivcs.agent.onCollectShortVideoResult(async data => {
		if (data.data.data.url) {
			data.data.data.url = AgentService.configure.replaceStaticUrl(data.data.data.url);
		}
		submitTask(data).then(resp => {
			callback(resp);
		});
	});
};

/** 提交任务 */
const submitTask = async (data: { from: string; data: any }) => {
	console.log('submitTask:', data);
	if (BusinessTaskMap.hasTask(data.from)) {
		await BusinessTaskMap.updateTaskStatus(data.from, data.data.status, data.data.id || null);
		const task = await BusinessTaskMap.getTask(data.from);
		if (task && (task.name === IBusinessName.SHARED_WHITEDOARD || task.name === IBusinessName.SHARED_PDF)) {
			await BusinessTaskMap.delTask(data.from);
		}
		if (task) {
			console.log('submitTask:', task, data.data);
			if (task.name !== IBusinessName.CUSTOMER_VIEW_MARK) {
				// 实时标注，不需要关心访客的完成情况
				await BusinessTaskMap.addCompletedTask({ task: task.name, data: task, response: data.data, isRead: false });
			}
			if (task.status === IBusinessStatus.REJECTED) {
				cancelBusinessMessage(task, data.data);
				// if (task.name === IBusinessName.CUSTOMER_VIEW_MARK) {
				// 	// 拒绝实时标注，移除视图
				// 	removeCustomerViewMarkContainer();
				// }
			} else if (task.status === IBusinessStatus.DONE) {
				doneBusinessMessage(task);
			}
			if (task.name === IBusinessName.SHARED_WHITEDOARD) {
				if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_WHITEDOARD).length === 0) {
					const result = await deleteWhiteboard(AgentService.whiteboardId);
					AgentService.whiteboardId = '';
				}
			} else if (task.name === IBusinessName.SHARED_PDF) {
				if (BusinessTaskMap.findTaskWithTaskName(IBusinessName.SHARED_PDF).length === 0) {
					const result = await deletePdfWhiteboard(AgentService.pdfWhiteBoardId);
					AgentService.pdfWhiteBoardId = '';
				}
			} else if (task.name === IBusinessName.CUSTOMER_VIEW_MARK) {
				// 实时标注
				AgentService.sendCustomerViewMarkEventData(data);
			}
		}
		return { clientId: data.from, data: task, response: data.data };
	}
};

const receiveCustomizeMessageData = (callBack: (data: any) => void) => {
	ivcs.agent.onCustomMessage(data => {
		console.log('receiveCustomizeMessageData:', data);
		if (data.data.type === 'broadcast') {
			callBack(data);
		}
	});
};

//取消/拒绝弹窗提示
const cancelBusinessMessage = (data: IBusiness, information: any) => {
	switch (data.name) {
		case IBusinessName.SEND_SIGN:
			Message.notify(t('client') + `<${data.username}>` + t('signature-canceled'));
			break;
		case IBusinessName.SEND_SCANNER_CODE:
			Message.notify(t('client') + `<${data.username}>` + t('scanning-canceled'));
			break;
		case IBusinessName.CUSTOMER_VIEW_MARK:
			Message.notify(t('client') + `<${data.username}>` + t('reject-customer-view-mark'));
			break;
		case IBusinessName.FILL_FORM:
			Message.notify(t('client') + `<${data.username}>` + t('form-fill-canceled'));
			break;
		case IBusinessName.SEND_IDCARD_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('id-card-collection-canceled'));
			break;
		case IBusinessName.SEND_BANKCARD_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('bank-card-collection-canceled'));
			break;
		case IBusinessName.TRANSCRIPT_OF_TESTIMONY:
			Message.notify(t('client') + `<${data.username}>` + t('testimony-transcript-canceled'));
			break;
		case IBusinessName.SEND_VARIABLE_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('variable-collection-canceled'));
			break;
		case IBusinessName.SHARED_PDF:
			Message.notify(t('client') + `<${data.username}>` + t('pdf-sharing-rejected'));
			break;
		case IBusinessName.SHARED_WHITEDOARD:
			Message.notify(t('client') + `<${data.username}>` + t('whiteboard-sharing-rejected'));
			break;
		case IBusinessName.SEND_VIDEO_COLLECTION:
			if (information.data.code && (information.data.code === '1023' || information.data.code === '60022')) {
				Message.info(t('client') + `<${data.username}>,` + t('unauthorized-camera-short-video-capture-failed') + '！');
			} else {
				Message.notify(t('client') + `<${data.username}>` + t('short-video-collection-canceled'));
			}
			break;
		default:
			break;
	}
};

//完成弹窗提示
const doneBusinessMessage = (data: IBusiness) => {
	switch (data.name) {
		case IBusinessName.SEND_SIGN:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-signature'));
			break;
		case IBusinessName.SEND_SCANNER_CODE:
			Message.notify(t('client') + `<${data.username}>` + t('scan-code-success'));
			break;
		case IBusinessName.FILL_FORM:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-form'));
			break;
		case IBusinessName.SEND_IDCARD_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-id-card-collection'));
			break;
		case IBusinessName.SEND_BANKCARD_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-bank-card-collection'));
			break;
		case IBusinessName.TRANSCRIPT_OF_TESTIMONY:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-testimony-transcript'));
			break;
		case IBusinessName.SEND_VARIABLE_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-variable-collection'));
			break;
		case IBusinessName.SEND_VIDEO_COLLECTION:
			Message.notify(t('client') + `<${data.username}>` + t('submitted-short-video-collection'));
			break;
		default:
			break;
	}
};

export {
	onScreenShot,
	onFillForm,
	onGeoLocation,
	onHandWriting,
	onScanCode,
	receiveCustomizeMessageData,
	onViewResource,
	onScreenCapture,
	onIdCardCollectResult,
	onBankCardCollectResult,
	onTestimonyWriteResult,
	onCollectVariableResult,
	onWhiteboardResult,
	onPdfWhiteboardResult,
	onCollectShortVideoResult,
	onCustomerViewMarkResult
};
